<template>
  <m-dialog
      title="设置主题"
      width="300px"
      v-model="dialog.visible"
      @close="close"
  >
    <div class="dialog-content">
      <el-color-picker v-model="colors.primary"></el-color-picker>
    </div>
    <span slot="footer" class="dialog-footer">
      <m-button @click="dialog.visible = false">取 消</m-button>
      <m-button type="primary" @click="setTheme">确 定</m-button>
    </span>
  </m-dialog>
</template>

<script>
import generateColors from '../../utils/theme/color'
import objectAssign from 'object-assign'

export default {
  name: "ChangeTheme",
  data() {
    return {
      originalStylesheetCount: -1,
      originalStyle: '',
      primaryColor: '#409eff',
      colors: {
        primary: '#409eff'
      },
      dialog: {
        visible: true
      }
    }
  },
  model:{
    prop: 'value'
  },
  props: ['value'],
  components: {},
  watch:{
    value:{
      handler: function (e){
        this.dialog.visible = e
      },
      immediate: true
    },
    originalStyle:{
      handler(e){
        this.colors.primary = this.theme
        this.setTheme()
      }
    }
  },
  created () {
    this.getIndexStyle()
  },
  computed:{
    theme() {
      return this.$store.state.MUI.settings.theme;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.originalStylesheetCount = document.styleSheets.length
    })
  },
  methods: {

    setTheme(){
      this.primaryColor = this.colors.primary
      this.colors = objectAssign({}, this.colors, generateColors(this.colors.primary))
      this.writeNewStyle()
      this.close()
    },
    writeNewStyle () {
      let cssText = this.originalStyle
      Object.keys(this.colors).forEach(key => {
        cssText = cssText.replace(new RegExp('(:|\\s+)' + key, 'g'), '$1' + this.colors[key])

      })
      // cssText = cssText.replace(new RegExp('fonts/element-icons.woff'), '//unpkg.com/element-ui/lib/theme-chalk/fonts/element-icons.woff')

      if (this.originalStylesheetCount === document.styleSheets.length) {
        const style = document.createElement('style')
        style.innerText = cssText
        document.head.appendChild(style)
      } else {
        document.head.lastChild.innerText = cssText
      }
    },
    getIndexStyle () {
      // this.getFile('//unpkg.com/element-ui/lib/theme-chalk/index.css')
      // .then(({ data }) => {
      //   this.originalStyle = this.getStyleTemplate(data)
      // })
      this.getFile('defaultTheme.css')
      .then(({ data }) => {
        this.originalStyle = this.getStyleTemplate(data)
      })
    },
    getStyleTemplate (data) {
      const colorMap = {
        '#3a8ee6': 'shade-1',
        '#409eff': 'primary',
        '#53a8ff': 'light-1',
        '#66b1ff': 'light-2',
        '#79bbff': 'light-3',
        '#8cc5ff': 'light-4',
        '#a0cfff': 'light-5',
        '#b3d8ff': 'light-6',
        '#c6e2ff': 'light-7',
        '#d9ecff': 'light-8',
        '#ecf5ff': 'light-9'
      }
      Object.keys(colorMap).forEach(key => {
        const value = colorMap[key]
        data = data.replace(new RegExp(key, 'ig'), value)
      })
      return data
    },
    getFile (url, isBlob = false) {
      return new Promise((resolve, reject) => {
        const client = new XMLHttpRequest()
        client.responseType = isBlob ? 'blob' : ''
        client.onreadystatechange = () => {
          if (client.readyState !== 4) {
            return
          }
          if (client.status === 200) {
            const urlArr = client.responseURL.split('/')
            resolve({
              data: client.response,
              url: urlArr[urlArr.length - 1]
            })
          } else {
            reject(new Error(client.statusText))
          }
        }
        client.open('GET', url)
        client.send()
      })
    },
    close(){
      this.$emit('input', false)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/MUI/style/var.scss";
.dialog-content{
  text-align: center;
}
</style>
